package utils

import (
	"bytes"
	jsoniter "github.com/json-iterator/go"
	"io/ioutil"
	"net/http"
)

func HttpPost(url string, body interface{}, headers map[string]string) (res []byte, err error) {
	var jsonBt []byte
	if body != nil {
		jsonBt, err = jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(body)
		if err != nil {
			return nil, err
		}
	}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBt))
	if err != nil {
		return nil, err
	}
	if headers != nil {
		for k, v := range headers {
			req.Header.Set(k, v)
		}
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}
